package com.lagou.service.biz;

import com.lagou.dao.AuthCodeDao;
import com.lagou.entity.AuthCode;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CodeBizService {

    @Autowired
    private AuthCodeDao authCodeDao;

    public AuthCode getCode(String code) {
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        return authCodeDao.findOne(Example.of(authCode)).orElse(null);
    }

    public AuthCode createCode(String email) {
        Date now = new Date();
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(RandomStringUtils.randomNumeric(4));
        authCode.setExpireTime(DateUtils.addMinutes(now, 10));
        authCode.setCreateTime(now);
        authCodeDao.saveAndFlush(authCode);
        return authCode;
    }

}
